package com.bob.clan.wxconnector.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;

/**
 * <br>
 * <b>功能：</b>操作日志拦截器<br>
 * <b>作者：</b>Wang Jiahao<br>
 * <b>日期：</b> Nov 9, 2014 <br>
 */
public class OperateLogInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(OperateLogInterceptor.class);
    private static ThreadLocal<Date> startTime = new ThreadLocal<Date>();

//    @Autowired
//    private MessageProducer producer;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //接收到请求，记录日志，记录到nosql中
        //添加截获操作
        startTime.set(new Date());

        StringBuffer msg = new StringBuffer();
        msg.append("\n");
        msg.append("客户端IP：[").append(request.getRemoteAddr()).append("]\n");
        msg.append("客户端真实IP：[");
        msg.append(getRealIp(request)).append("]\n");
        msg.append("客户端HTTPURL：[").append(request.getRequestURL()).append("]\n");
        msg.append("请求方式：[").append(request.getMethod()).append("]\n");
        msg.append("开始执行时间：[").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        msg.append("SessionId：[").append(request.getSession().getId()).append("]\n");
//        msg.append("Session：[");
//        msg.append(JSON.toJSONString(request.getSession())).append("]\n");
        msg.append("请求地址：[uri＝").append(request.getRequestURI()).append("]\n");
        Enumeration<String> enumeration = request.getParameterNames();
        msg.append("请求参数：[");
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            String[] values = request.getParameterValues(name);
            msg.append(name).append("=");
            if (values != null) {
                int i = 0;
                for (String value : values) {
                    i++;
                    msg.append(value);
                    if (i < values.length) {
                        msg.append("｜");
                    }
                }
                msg.append("\n");
            }
        }
        msg.append("]");

        //记录在日志文件中
        logger.info(msg.toString());
//        producer.sendMessage("directExchange", "directRoutingKey", msg.toString());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        StringBuffer msg = new StringBuffer();
        Date endTime = new Date();
        msg.append("结束执行时间：[").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        msg.append("总耗时：[").append(endTime.getTime() - startTime.get().getTime()).append("ms]\n");
        logger.info(msg.toString());
    }

    private String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
